<!--
 * @Description: vscode自带注释
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-04-10 21:56:40
 * @LastEditors: lhl
 * @LastEditTime: 2021-05-04 19:41:32
-->
<template>
  <van-popup v-model:show="showPicker" v-bind="popupConfig">
    <van-picker
      show-toolbar
      swipe-duration="300"
      :title="$t('langSelect.pickerTitle')"
      :columns="langs"
      :default-index="defaultIndex"
      @confirm="onConfirm"
      @cancel="onClose"
    />
  </van-popup>
</template>

<script>
  import { defineComponent, toRefs, reactive, onMounted, getCurrentInstance, computed } from 'vue'
  import { useStore } from 'vuex'
  import { Locale } from 'vant'
  import { setLanguage } from '@/utils/cookies'

  export default defineComponent({
    name: 'LangSelect',
    props: {
      popupConfig: {
        type: Object,
        default: () => ({
          overlay: true,
          position: 'bottom',
          duration: 0.3,
          closeOnPopstate: true,
          transitionAppear: true,
          safeAreaInsetBottom: true
        })
      }
    },
    setup() {
      const state = reactive({
        langs: [
          {
            text: '中文（简体）',
            value: 'zh-CN'
          },
          {
            text: '中文（繁体）',
            value: 'zh-TW'
          },
          {
            text: 'English',
            value: 'en-US'
          },
          {
            text: '日本語',
            value: 'ja-JP'
          }
        ]
      })
      const store = useStore()
      const { proxy } = getCurrentInstance()
      console.log(store, 'store', getCurrentInstance(), 'getCurrentInstance')
      const computedData = {
        showPicker: computed(() => store.getters.langPicker),
        defaultIndex: computed(
          () => state.langs.findIndex((item) => item.value === proxy.$i18n.locale) || 0
        )
      }
      const methods = {
        onConfirm({ value }) {
          // Vant basic
          Locale.use(value, proxy.$i18n.messages[value])
          // Business component
          proxy.$i18n.locale = value
          // Cookie
          setLanguage(value)
          store.commit('hideLangPicker', false)
        },
        onClose() {
          store.commit('hideLangPicker', false)
        }
      }
      return {
        ...toRefs(state),
        ...methods,
        ...computedData
      }
    }
  })
</script>

<style lang="less" scoped></style>
